package com.kehutong.contact.service.impl;

import com.kehutong.contact.entity.Contact;
import com.kehutong.contact.entity.ContactDynamics;
import com.kehutong.contact.entity.Customer;
import com.kehutong.contact.enums.FollowUpType;
import com.kehutong.contact.service.ContactDynamicsService;
import com.kehutong.contact.service.ContactService;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSON;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindPage;

import java.util.List;
import java.util.Objects;

/**
 * @author liujinwang
 * description:
 */
@WebService("/crm/contact/service")
public class ContactServiceImpl implements ContactService {

    private static final Logger logger = LoggerFactory.getLogger(ContactServiceImpl.class);

    @Inject
    private JdbcSession jdbcSession;

    @Inject
    private ContactDynamicsService contactDynamicsService;

    @Override
    public Page<Contact> page(JSONObject jsonObject) {
        FindPage<Contact> find = jdbcSession.findPage(Contact.class)
                .eq(jsonObject, "id", "customerId")
                .like(jsonObject, "corpFullName", "contactName", "mobile", "position")
                .eq("deleted", false);
        //添加选中导出条件
        JSONArray exportIdList = jsonObject.getJSONArray("exportIdList");
        if(Objects.nonNull(exportIdList)){
            find.in("id",exportIdList);
        }
        return find.order("createTime", "desc").page(jsonObject).exe();
    }

    @Override
    public Object list(JSONObject jsonObject) {
        return jdbcSession.findArray(Contact.class)
                .eq(jsonObject,  "id")
                .like(jsonObject, "corpFullName","contactName", "mobile", "position")
                .eq("deleted",false)
                .order("createTime", "desc")
                .exe();
    }

    @Bean(newInstance = true, copy = true)
    @ReqMapping("/save")
    @Override
    public Object save(Contact contact){
        checkSave(contact);
        jdbcSession.insert(contact);
        ContactDynamics contactDynamics = Pool.newInstance(ContactDynamics.class);
        buildContactDynamics(contact,contactDynamics);
        jdbcSession.insert(contactDynamics);
        return Result.success(contact);
    }

    private void checkSave(Contact contact) {
        Contact isExistContact = jdbcSession.findOne(Contact.class)
                .eq("contactName", contact.getContactName())
                .eq("mobile", contact.getMobile())
                .eq("customerId",contact.getCustomerId())
                .eq("deleted", false)
                .exe();
        if(org.coraframework.util.Objects.nonNull(isExistContact)){
            throw new RuntimeException("该联系人已经存在");
        }
    }

    private void buildContactDynamics(Contact contact, ContactDynamics contactDynamics) {
        contactDynamics.setCustomerId(contact.getCustomerId());
        contactDynamics.setType(FollowUpType.DATA);
        contactDynamics.setCorpFullName(contact.getCorpFullName());
        contactDynamics.setFollowUpName(contact.getFollowUpName());
        contactDynamics.setFollowUpId(contact.getFollowUpId());
        contactDynamics.setContactId(contact.getId());
        contactDynamics.setContactName(contact.getContactName());
    }

    @Override
    public Object update(Contact contact) {
        jdbcSession.updateById(contact);
        if (contact.isFirstContact()) {
            Customer customer = Pool.get(Customer.class, contact.getCustomerId());
            buildCustomer(customer,contact);
            jdbcSession.updateById(customer);
        }
        return Result.success(contact);
    }

    @Override
    public Object delete(JSONObject jsonObject) {
        List<Contact> contactList = jdbcSession.findArray(Contact.class)
                .in("id", jsonObject.getJSONArray("ids"))
                .eq("deleted",false)
                .exe();
        contactList.forEach(item ->{
            if (item.isFirstContact()) {
                throw new RuntimeException("请更换首联系人，再尝试删除~");
            }
        });
        contactList.forEach(item ->{
            item.setDeleted(true);
            jdbcSession.updateById(item,item.getId());
        });
        return Result.success("删除成功：" + contactList.size() + "条");
    }

    /**
     * 客户联系人列表
     * @param jsonObject
     * @return
     */
    @ReqMapping("/contactList")
    @Override
    public Object getContactList(JSONObject jsonObject) {
        String customerId = jsonObject.getString("customerId");
        if (Objects.isNull(customerId)) {
            return Result.error(0,"客户id不能为空");
        }
        return jdbcSession.findPage(Contact.class)
                .eq(jsonObject,  "customerId")
                .eq("deleted",false)
                .order("createTime", "desc")
                .exe();
    }

    /**
     *设置首联系人
     * @param jsonObject
     * @return
     */
    @ReqMapping("/update/firstContact")
    @Override
    public Object updateFirstContact(JSONObject jsonObject) {
        String customerId = jsonObject.getString("customerId");
        String contactId = jsonObject.getString("id");
        Contact isExitContact = jdbcSession.findOne(Contact.class)
                .eq("customerId", customerId)
                .eq("firstContact", true)
                .eq("deleted", false)
                .exe();
        if (Objects.nonNull(isExitContact)) {
            isExitContact.setFirstContact(false);
            jdbcSession.updateById(isExitContact);
        }
        Contact contact = jdbcSession.findOne(Contact.class).eq(jsonObject, contactId).eq("deleted", false).exe();
        if (Objects.isNull(contact)) {
            return Result.error(0,"当前联系人已删除");
        }
        contact.setFirstContact(true);
        jdbcSession.updateById(contact);
        Customer customer = Pool.get(Customer.class, customerId);
        buildCustomer(customer,contact);
        jdbcSession.updateById(customer);
        return Result.success();
    }

    private void buildCustomer(Customer customer, Contact contact) {
        customer.setContactName(contact.getContactName());
        customer.setContactId(contact.getId());
        customer.setCorpFullName(contact.getCorpFullName());
        customer.setSirOrLady(contact.getSirOrLady());
        customer.setRole(contact.getRole());
        customer.setBirthday(contact.getBirthday());
        customer.setPosition(contact.getPosition());
        customer.setMobile(contact.getMobile());
        customer.setTelephone(contact.getTelephone());
        customer.setFax(contact.getFax());
        customer.setEmail(contact.getEmail());
        customer.setWechat(contact.getWechat());
        customer.setQq(contact.getQq());
        customer.setAreaName(contact.getAreaName());
        customer.setDetailAddress(contact.getDetailAddress());
        customer.setRemarkMsg(contact.getRemarkMsg());
        customer.setFollowUpName(contact.getFollowUpName());
        customer.setFollowUpId(contact.getFollowUpId());
        customer.setFirstContact(contact.isFirstContact());
    }
}
